package com.qingke.besuperdb;

import java.util.List;

public class BeSuperApp {
	private static final String LOGIN="login";
	private static final String REGISTER="register";
	private static final String LIST="list";
	private static final String LIST_P="list -p";
	private static final String LIST_Q="list -q";
	private static final String LIST_A="list -a";
	private static final String ASK="ask";
	private static final String ANSWER="answer";
	private static final String SCORE="score";
	private static final String HELP="help";
	private static final String EXIT="exit";
//	private static final String SEARCH="search";
	private static final String MODELALL="all";
	private static final String MODELMINE="mine";
	private static final String MODELOPEN="open";
	private static final String MODELID="id";
	private static final String OPEN="open";
	private static final String CLOSE="close";
	private static final String BEST="best";
	
	
	private User user;
	private BeSuperDAO dao;
	
	public BeSuperApp(){
		
	}

	public void init(){
		dao=new BeSuperDAO();
	}
	
	public boolean login(){
		BeSuperConsole.println();
		BeSuperConsole.println("----------------");
		String username=BeSuperConsole.promptNotEmpty("username:");
		String password=BeSuperConsole.promptNotEmpty("password:");
		BeSuperConsole.println("----------------");
		
		user=dao.login(username, password);
		
		if(user==null)
			return false;
		else
			return true;
	}
	
	public boolean register(){
		BeSuperConsole.println("----------------");
		String nickname=BeSuperConsole.promptNotEmpty("nickname:");
		String username=BeSuperConsole.promptNotEmpty("username:");
		String password=BeSuperConsole.promptNotEmpty("password:");
		BeSuperConsole.println("----------------");
		
		boolean isSuccess=dao.register(nickname, username, password);
		return isSuccess;
	}
	
	public boolean pass(){
		BeSuperConsole.println("Welcome to BeSuper.");
		String command;
		while(true){
			BeSuperConsole.println("Please login or register.");
			command=BeSuperConsole.prompt("input:").trim();
			if(LOGIN.equalsIgnoreCase(command)){
				if(login()){
					BeSuperConsole.println("Login success.");
					BeSuperConsole.println();
					return true;
				}
				else{
					BeSuperConsole.println("Login failed.");
					BeSuperConsole.println();
				}
			}
			else if(REGISTER.equalsIgnoreCase(command)){
				if(register()){
					BeSuperConsole.println("Register success.");
				}
				else{
					BeSuperConsole.println("Register failed,the username has been used.");
					
				}
			}
			else if(HELP.equalsIgnoreCase(command)){
				helpPass();
			}
			else if(EXIT.equalsIgnoreCase(command)){
				exitPass();
				return false;
			}
			else{
				errPass();
			}
		}
	}
	
	public void run() {
		
		init();
		
		if(!pass()){
			return ;
		}
		
		BeSuperConsole.println("Hello,"+this.user.getName());
		BeSuperConsole.println("you can input help to look command");
		String command;
		while(true){
			command=BeSuperConsole.prompt("cmd>").trim();
			if(LIST.equalsIgnoreCase(command)){
				listCommand();
			}
			else if(LIST_P.equalsIgnoreCase(command)){
				listPCommand();
			}
			else if(LIST_Q.equalsIgnoreCase(command)){
				listQCommand();
			}
			else if(LIST_A.equalsIgnoreCase(command)){
				listACommand();
			}
			else if(ASK.equalsIgnoreCase(command)){
				askCommand();
			}
			else if(ANSWER.equalsIgnoreCase(command)){
				answerCommand();
			}
			else if(OPEN.equalsIgnoreCase(command)){
				updateQuestionIsOpen(true);
			}
			else if(CLOSE.equalsIgnoreCase(command)){
				updateQuestionIsOpen(false);
			}
			else if(BEST.equalsIgnoreCase(command)){
				listMineQuestions();
				chooseBestAnswer();
			}
			else if(SCORE.equalsIgnoreCase(command)){
				scoreCommand();
			}
			else if(HELP.equalsIgnoreCase(command)){
				helpCommand();
			}
			else if(EXIT.equalsIgnoreCase(command)){
				exitCommand();
				break;
			}
//			else if(SEARCH.equalsIgnoreCase(command)){
//				search();
//			}
			else{
				errCommand();
			}
			
		}
		
	}
	
	public void listCommand(){
		BeSuperConsole.println("Please use [list -p],[list -q] or [list -a].");
	}
	public void listPCommand(){
		List<User> arrU = dao.listAllUsers();
		BeSuperConsole.println("------player list------");
		for(User u:arrU){
			BeSuperConsole.println("id:["+u.getId()+"],name:["+u.getName()+"],score:["+u.getScore()+"]");
		}
		BeSuperConsole.println();
	}
	public void listQCommand(){
		String model;
		while(true){
			model=BeSuperConsole.prompt("model:").trim();
			if(MODELALL.equalsIgnoreCase(model)){
				listAllQuestions();
			}
			else if(MODELMINE.equalsIgnoreCase(model)){
				listMineQuestions();
			}
			else if(MODELOPEN.equalsIgnoreCase(model)){
				listOpenQuestions();
			}
			else if(MODELID.equalsIgnoreCase(model)){
				listQuestionByQuestionId();
				
			}
			else if(HELP.equalsIgnoreCase(model)){
				helpModel();
				continue;
			}else if(EXIT.equalsIgnoreCase(model)){
				BeSuperConsole.println("You give up to list");
				BeSuperConsole.println();
			}
			else{
				errModel();
				continue;
			}
			break;
		}
	}
	public void listAllQuestions(){
		List<Question> arr=dao.listAllQuestions();
		BeSuperConsole.println("------all questions list------");
		for(Question q:arr){
			BeSuperConsole.println("id:["+q.getId()+"],credit:["+q.getCredit()+"],questioner:["+q.getPlayerId()+"],isOpen:["+q.isOpen()+"],context:"+q.getContext());
		}
	}
	public void listMineQuestions(){
		List<Question> arr=dao.listMineQuestions(user.getId());
		BeSuperConsole.println("------my questions list------");
		for(Question q:arr){
			BeSuperConsole.println("id:["+q.getId()+"],credit:["+q.getCredit()+"],questioner:["+q.getPlayerId()+"],isOpen:["+q.isOpen()+"],context:"+q.getContext());
		}	
	}
	public void listOpenQuestions(){
		List<Question> arr=dao.listOpenQuestions(true);
		BeSuperConsole.println("------opened questions list------");
		for(Question q:arr){
			BeSuperConsole.println("id:["+q.getId()+"],credit:["+q.getCredit()+"],questioner:["+q.getPlayerId()+"],isOpen:["+q.isOpen()+"],context:"+q.getContext());
		}
	}
	public void listQuestionByQuestionId(){
		int idInt=-1;
		String idStr="";
		while(true){
			idStr=BeSuperConsole.promptNotEmpty("input the question's id:").trim();
			if(idStr.replaceAll("[0-9]","").equals("")){
				idInt=Integer.parseInt(idStr);
			}
			else{
				BeSuperConsole.println("err input");
				continue;
			}
			break;
		}
		Question q=dao.listQuestionByQuestionId(idInt);
		
		if(q!=null){
			BeSuperConsole.println("------the id of the question list------");
			int bestAnswerId=q.getBestAnswerId();
			if(bestAnswerId==-1){
				BeSuperConsole.println("id:["+q.getId()+"],credit:["+q.getCredit()+"],questioner:["+q.getPlayerId()+"],isOpen:["+q.isOpen()+"],context:"+q.getContext());
			}
			else{
				BeSuperConsole.println("id:["+q.getId()+"],credit:["+q.getCredit()+"],questioner:["+q.getPlayerId()+"],bset answer id:["+q.getBestAnswerId()+"]isOpen:["+q.isOpen()+"],context:"+q.getContext());
			}
			
			listAnswersByQuestionId(q.getId());
		}
		else{
			BeSuperConsole.println("the id of the question is not exited.");
		}
	}
	public void listAnswersByQuestionId(int questionId){
		Question q=dao.listQuestionByQuestionId(questionId);
		List<Answer> arrA=dao.listAnswersByQuestionId(questionId);
		
		if(q!=null){
			int bestAnswerId=q.getBestAnswerId();
			if(bestAnswerId==-1){
				BeSuperConsole.println("------the question of answers list------");
				for(Answer a:arrA){
					BeSuperConsole.println("id:["+a.getId()+"],answerer:["+a.getPlayerId()+"],value:"+a.getValue());
				}
			}
			else{
				BeSuperConsole.println("------the best answer------");
				for(Answer a:arrA){
					if(a.getId()==bestAnswerId)
						BeSuperConsole.println("id:["+a.getId()+"],answerer:["+a.getPlayerId()+"],value:"+a.getValue());
				}
				
				BeSuperConsole.println("------the question of answers list------");
				for(Answer a:arrA){
					if(a.getId()!=bestAnswerId)
						BeSuperConsole.println("id:["+a.getId()+"],answerer:["+a.getPlayerId()+"],value:"+a.getValue());
				}
			}
		}
		else{
			BeSuperConsole.println("the id of the question is not exited.");
		}
	}
	public void listACommand(){
		List<Answer> arrA=dao.listAllAnswer();
		BeSuperConsole.println("------answer list------");
		for(Answer a:arrA){
			BeSuperConsole.println("id:["+a.getId()+"],question id:["+a.getQuestionId()+"],answerer id:["+a.getPlayerId()+"],context:"+a.getValue());
			
		}
		BeSuperConsole.println();
	}
	public void askCommand(){
		String context;
		String creditStr;
		int creditInt;
		int length;
		while(true){
			context=BeSuperConsole.promptNotEmpty("Please input question:");
			length=context.length();
			if(length>45){
				BeSuperConsole.println("You can only enter 45 characters.");
				BeSuperConsole.println();
				continue;
			}
			break;
		}
		while(true){
			creditStr=BeSuperConsole.promptNotEmpty("Please input credit:").trim();
			if(creditStr.trim().replaceAll("[0-9]","").equals("")){
				creditInt=Integer.parseInt(creditStr);
			}
			else{
				BeSuperConsole.println("Please input right credit.");
				BeSuperConsole.println();
				continue;
			}
			break;
		}
		if(creditInt<0){
			creditInt=0;
			BeSuperConsole.println("You set the question's credit = "+creditInt+" .");
			BeSuperConsole.println();
		}
		else if(creditInt>this.user.getScore()){
			creditInt=this.user.getScore();
			user.setScore(0);;
			BeSuperConsole.println("The credit you set is more than your score,");
			BeSuperConsole.println("so the credit is setted to your all score , credit = "+creditInt+" .");
			BeSuperConsole.println();
		}
		else{
			BeSuperConsole.println("You set the question's credit = "+creditInt+" .");
			BeSuperConsole.println();
		}
		
		int isSuccess=dao.ask(context, creditInt,this.user.getId());
		if(isSuccess>0)
			BeSuperConsole.println("ask success");
		else
			BeSuperConsole.println("ask failed");
			
		
		
	}
	public void answerCommand(){
		String num=BeSuperConsole.promptNotEmpty("Please input question id:").trim();
		if(!num.replaceAll("[0-9]","").equals("")){
			BeSuperConsole.println("err input");
			return ;
		}
		int questionId=Integer.parseInt(num);
		
		Question q=dao.listQuestionByQuestionId(questionId);
		if(q==null){
			BeSuperConsole.println("do not exist the id of the question");
			return ;
		}
		if(!q.isOpen()){
			BeSuperConsole.println("the question is not opened");
			return ;
		}
		
		BeSuperConsole.println(q.getContext());
		String value=BeSuperConsole.promptNotEmpty("your answer:");
		
		int isTrue=dao.insertAnswer(value, questionId, this.user.getId());
		if(isTrue>0)
			BeSuperConsole.println("answer success");
		else
			BeSuperConsole.println("answer failed");
		
		
	}
	public void scoreCommand(){
		BeSuperConsole.println("your score:"+this.user.getScore());
		
		List<Question> arrQ=dao.listMineQuestions(user.getId());
		BeSuperConsole.println("------your questions:"+arrQ.size()+"------");
		for(Question q:arrQ){
			BeSuperConsole.println("id:["+q.getId()+"],credit:["+q.getCredit()+"],isOpen:["+q.isOpen()+"],context:"+q.getContext());
		}
		
		List<Answer> arrA=dao.listAnswersByUserId(user.getId());
		BeSuperConsole.println("------your answers:"+arrA.size()+"------");
		for(Answer a:arrA){
			BeSuperConsole.println("id:["+a.getId()+"],question id:["+a.getQuestionId()+"],context:"+a.getValue());
		}
		
	}
	public void chooseBestAnswer(){
		String num=BeSuperConsole.promptNotEmpty("Please input question id:").trim();
		if(!num.replaceAll("[0-9]","").equals("")){
			BeSuperConsole.println("err input");
			return ;
		}
		int questionId=Integer.parseInt(num);
		Question q=dao.listQuestionByQuestionId(questionId);
		if(q.getPlayerId()!=this.user.getId()){
			BeSuperConsole.println("It's not your question.");
			return ;
		}
		
		List<Answer> arrA=dao.listAnswersByQuestionId(questionId);
		if(arrA.size()==0){
			BeSuperConsole.println("The question no answer.");
			return ;
		}
		
		listAnswersByQuestionId(q.getId());
		BeSuperConsole.println();
		
//		BeSuperConsole.println("------the question------");
//		BeSuperConsole.println(q.getContext());
		
		String bestStr=BeSuperConsole.promptNotEmpty("input best answer's id:").trim();
		if(!bestStr.replaceAll("[0-9]","").equals("")){
			BeSuperConsole.println("err input");
			return ;
		}
		int newBest=Integer.parseInt(bestStr);
		int oldBest=q.getBestAnswerId();
		
		Answer newA=dao.listAnswerByAnswerId(newBest);
		Answer oldA=dao.listAnswerByAnswerId(oldBest);
		
		if(newA==null){
			BeSuperConsole.println("The answer is not exited.");
			return ;
		}
		
		if(!arrA.contains(newA)){
			BeSuperConsole.println("The answer you choose is not one of the question'answers.");
			return ;
		}
		
		if(newBest==oldBest){
			BeSuperConsole.println("The answer is already the best answer.");
			return ;
		}

		
		int isSuccess=dao.updateBestAnswer(questionId, newBest);
		if(isSuccess>0){
			User newU=dao.listUserByUserId(newA.getPlayerId());
			int newSuccess=dao.updateScore(newU.getId(),newU.getScore()+q.getCredit());
			int oldSuccess=1;
			
			if(oldA!=null){
				User oldU=dao.listUserByUserId(oldA.getPlayerId());
				oldSuccess=dao.updateScore(oldU.getId(),oldU.getScore()-q.getCredit());
			}
			
			if(newSuccess>0&&oldSuccess>0){
				BeSuperConsole.println("Choose the best answer success");
				return ;
			}
		}
		BeSuperConsole.println("Choose the best answer failed");
			
			
	}
	public void updateQuestionIsOpen(boolean isOpen){
		String isOpenStr;
		if(isOpen)
			isOpenStr="open";
		else
			isOpenStr="close";
		String num=BeSuperConsole.promptNotEmpty("Please input question id:").trim();
		if(!num.replaceAll("[0-9]","").equals("")){
			BeSuperConsole.println("err input");
			return ;
		}
		int questionId=Integer.parseInt(num);
		Question q=dao.listQuestionByQuestionId(questionId);
		if(q.getPlayerId()!=this.user.getId()){
			BeSuperConsole.println("It's not your question.");
			return ;
		}
		if(q.isOpen()){
			BeSuperConsole.println("The question have been "+isOpenStr+"ed.");
			return ;
		}
		int isSuccess=dao.updateIsOpen(q.getId(),isOpen);
		if(isSuccess>0)
			BeSuperConsole.println(isOpenStr+" success");
		else
			BeSuperConsole.println(isOpenStr+" failed");
			
	}

	public void helpCommand(){
		BeSuperConsole.println("- list -p   list all players and their score");
		BeSuperConsole.println("- list -q   list all questions");
		BeSuperConsole.println("- list -a   list all answers");
		BeSuperConsole.println("- ask       ask a question");
		BeSuperConsole.println("- answer    select a question to answer");
		BeSuperConsole.println("- open      set a question to open");
		BeSuperConsole.println("- close     set a question to close");
		BeSuperConsole.println("- best      choose a best answer for a question");
		BeSuperConsole.println("- score     show your score");
		BeSuperConsole.println("- help      list all commands");
		BeSuperConsole.println("- exit      quit beSuper");
	}
	public void helpModel(){
		BeSuperConsole.println("- all    list all questions");
		BeSuperConsole.println("- mine   list the questions you ask");
		BeSuperConsole.println("- open   list the question opened");
		BeSuperConsole.println("- id     list the id of the question");
		BeSuperConsole.println("- help   list all models");
		BeSuperConsole.println("- exit   quit list");
	}
	public void helpPass(){
		BeSuperConsole.println("- login      login besuper system");
		BeSuperConsole.println("- register   register a user");
		BeSuperConsole.println("- help       list all pass command");
		BeSuperConsole.println("- exit       quit pass");
	}
	public void exitCommand(){
		BeSuperConsole.println("Bye bye");
	}
	public void exitPass(){
		BeSuperConsole.println("Bye bye");
	}
	public void errCommand(){
		BeSuperConsole.println("err input");
		BeSuperConsole.println("you can input help to look command");
	}
	public void errModel(){
		BeSuperConsole.println("err input");
		BeSuperConsole.println("you can input help to look model");
	}
	public void errPass(){
		BeSuperConsole.println("err input");
		BeSuperConsole.println("you can input help to look pass command");
	}
	
//	public void search(){
//		CallableStatement cs = null;
//		try {
//			String pattern=BeSuperConsole.prompt("Enter username pattern:");
//			sql="call besuper.get_player(?,?);";
//			cs=conn.prepareCall(sql);
//			cs.setString(1,pattern);
//			cs.registerOutParameter(2,Types.INTEGER);
//			
//			cs.execute();
//			int resultCount=cs.getInt(2);
//			BeSuperConsole.println("count = "+resultCount);
//			rs=cs.getResultSet();
//			while(rs.next()){
//				String id = rs.getString("id");
//				String name = rs.getString("name");
//				int score = rs.getInt("score");
//				BeSuperConsole.println("Player [ id = "+id+" , name = "+name+" , score = "+score+" ]");
//			}
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
//	}
}
